﻿using ChatBackend.Entity;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace ChatBackend.DBContext
{
    public static class SqlSugarContextExtend
    {
        public static void AddSqlsugar(this IServiceCollection Services)
        {
            //注册SqlSugar
            Services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.SqlServer,
                    ConnectionString = "server=.;database=ChatDB;uid=sa;pwd=12345678;TrustServerCertificate=true;",
                    IsAutoCloseConnection = true,
                },
               db =>
               {
                   //单例参数配置，所有上下文生效
                   //执行前控制台输出sql
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                   };

                   db.Aop.DataExecuting = (oldValue, entityInfo) =>
                   {
                       /*** 列级别事件：插入的每个列都会进事件 ***/
                       if (entityInfo.PropertyName == "CreateTime" && entityInfo.OperationType == DataFilterType.InsertByObject)
                       {
                           entityInfo.SetValue(DateTime.Now);//修改CreateTime字段
                       }
                       if (entityInfo.PropertyName == "CreateBy" && entityInfo.OperationType == DataFilterType.InsertByObject)
                       {
                           //todo
                       }
                       if (entityInfo.PropertyName == "IsDelete" && entityInfo.OperationType == DataFilterType.InsertByObject)
                       {
                           entityInfo.SetValue(false);
                       }
                       if (entityInfo.PropertyName == "ModifyTime" && entityInfo.OperationType == DataFilterType.UpdateByObject)
                       {
                           entityInfo.SetValue(DateTime.Now);//修改ModifyTime字段
                       }
                       if (entityInfo.PropertyName == "ModifyBy" && entityInfo.OperationType == DataFilterType.UpdateByObject)
                       {
                           //todo
                       }
                   };

                   //表过滤器，过滤表中所有isdelete=false的列  设置连表生效
                   db.QueryFilter.AddTableFilter<BaseEntity>(x => x.IsDelete == false, QueryFilterProvider.FilterJoinPosition.Where);
               });
                return sqlSugar;
            });
        }
    }
}